import copy

from databases.base_db import BaseDb

import sqlalchemy
from sqlalchemy import *

from sqlalchemy.sql import text

class Alchemy(BaseDb):
    engine = None
    conn = None
    meta = None
    
    def __init__(self, config):
        self.meta = MetaData()
        self.engine = create_engine(config)
        self.conn = self.engine.connect()
        self.meta.bind = self.engine

    def get_version(self):
        s = text("SELECT version FROM schema_info")
        result = ['000']
        try:
            result = self.conn.execute(s).fetchone()
        except Exception, e:
            self._create_schema()

        return int(result[0])

    def update_schema(self, version):
        schema = self._schema_table()
        self.conn.execute(schema.update(), [{'version' : version}])

    def execute(self, query):
        self.conn.execute(query)

    def execute_drop_table(self, table):
        table.drop(checkfirst=True)
        
    def execute_drop_column(self, table, column):
        table.c[column].drop()

    def execute_raw_query(self, query):
        return self.conn.execute(query)

    def close(self):
        self.conn.close()

    def format_table(self, name):
        return sqlalchemy.Table(name, self.meta, autoload=True)

#==============================================
# Private Methods
#==============================================

    def _create_schema(self):
        schema_info = self._schema_table()
        self.meta.create_all()
        self.conn.execute(schema_info.insert(), [{'version' : '000'}])

    def _schema_table(self):
        schema_info = Table('schema_info', self.meta,
            Column('version', String(30)),
            useexisting=True
            )
        return schema_info